package com.zues.thread.lock.cas.lock;

import com.zues.thread.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zues
 * @date 3/12/2025 8:56 下午
 */
@Slf4j(topic = "c.LockCasDemo1")
public class LockCasDemo1 {

    /*
     * 0 未加锁
     * 1 加锁
     */
    private AtomicInteger state = new AtomicInteger(0);

    public void lock() {
        while (true) {
            if (state.compareAndSet(0, 1)) {
                break;
            }
        }
    }

    public void unlock() {
        log.debug("unlock...");
        state.set(0);
    }


    public static void main(String[] args) {
        LockCasDemo1 lock = new LockCasDemo1();
        new Thread(() -> {
            log.debug("begin...");
            lock.lock();
            try {
                log.debug("locking...");
                ThreadUtil.sleep(1 );
            } finally {
                lock.unlock();
            }
        }, "t1").start();


        new Thread(() -> {
            log.debug("begin...");
            lock.lock();
            try {
                log.debug("locking...");
            } finally {
                lock.unlock();
            }
        }, "t2").start();
    }


}
